<template>
    <section class="power-user-control" @click="treeBlurHide">
        <div class="user-filter">
            <el-form ref="user-filter" :model="searchForm" :inline="true" class="demo-form-inline" label-position="top" >
                <el-row>
                    <el-col :span="4">
                        <el-form-item label="用户名:" label-width="80px">
                            <el-input size="small" v-model="searchForm.name" placeholder="请输入用户名"></el-input>
                        </el-form-item>
                    </el-col>
                     <el-col :span="4">
                        <el-form-item label="账号:" label-width="80px">
                            <el-input size="small" v-model="searchForm.account" placeholder="请输入账号"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4" >
                        <el-form-item label="所属部门:" label-width="80px">
                            <el-input v-model="searchForm.departmentName"  size="small" icon="caret-bottom" placeholder="请选择部门"></el-input>
                            <div @click.stop="searchForm.showTree=!searchForm.showTree"
                                 style="position: absolute;top:3px;left:0;z-index: 10;min-width: 260px;max-width: 100%;height: 30px;">
                                <div v-show="searchForm.showTree" class="department-tree-select" >
                                    <el-tree size="small" :data="departmentTree"
                                             :props="departmentTreeProps"
                                             :load="loadNode"
                                             @check-change="handleSearchCheckChange"
                                             node-key="id" ref="searchTree"
                                             check-strictly accordion
                                             highlight-current show-checkbox
                                             lazy>
                                    </el-tree>
                                </div>
                            </div>
                        </el-form-item>
                    </el-col>
                   
                    <el-col :span="4">
                        <el-form-item label="岗位信息:" label-width="80px">
                            <job-select ref="jobName" from="searchForm"/>
                        </el-form-item>
                    </el-col>
                </el-row>
               
                <el-row>
                	<div style="height: 10px;"></div>
                        <el-button type="primary" @click="clearSearchForm" icon="el-icon-delete" size="small" style="margin-bottom: 5px"> 清空筛选条件</el-button>
                        <el-button type="primary" @click="query" icon="el-icon-search" size="small"> 查询</el-button>
                 <div style="height: 10px;"></div>
                </el-row>
            </el-form>
        </div>

        <div class="user-table">
            <div class="tool-bar">
                <nuxt-link :to="{name:'power-user-control-name',params:{name:'add'}}"><el-button icon="el-icon-plus" @click="" size="small"> 添加</el-button></nuxt-link>
                <el-button @click="refresh" size="small"><i class="fa fa-refresh"></i>&nbsp;&nbsp;刷新</el-button>
            </div>

            <el-table :data="userDatas"
                      :default-sort = "{prop: 'lastLoginTime', order: 'descending'}"
                    border style="width: 100%"  stripe highlight-current-row>
                <!--<el-table-column type="index" align="center"></el-table-column>
                <el-table-column label="操作"  align="center">
                    <template scope="scope">
                        <a v-show="scope.row.status > 1" class="oprate-item" @click="regainUser(scope.$index)" href="javascript:void(0)">启用</a>
                        <a v-show="scope.row.status === 1" class="oprate-item" @click="freezeUser(scope.$index)" href="javascript:void(0)">冻结</a>
                        <a v-show="scope.row.status === 1" class="oprate-item" @click="disableUser(scope.$index)" href="javascript:void(0)">停用</a>
                        <a class="oprate-item" @click="resetPwd(scope.$index)" href="javascript:void(0)">重置密码</a>
                        <a class="oprate-item" @click="distributeRole(scope.$index)" href="javascript:void(0)">分配岗位</a>
                    </template>
                </el-table-column>-->
                <el-table-column label="用户名" width="" align="center">
                    <template scope="scope">
                        <a class="oprate-item" @click="detail(scope.row.id)" href="javascript:void(0)">{{scope.row.name}}</a>
                    </template>
                </el-table-column>
                <el-table-column prop="account" label="账号" width="" align="center"></el-table-column>
                <el-table-column  width="200" label="部门-岗位" align="center">
                    <template scope="scope">
                        <div>
                            <span>{{scope.row.departmentName}}</span>-<span>{{scope.row.jobName}}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="lastLoginTime" sortable label="最近登录时间" align="center"> </el-table-column>
                <el-table-column label="操作" fixed="right" align="center">
                    <template scope="scope">
                        <el-button size="mini" @click.native.prevent="edit(scope.row)" icon="el-icon-edit" type="primary" style="margin: 2px">编辑</el-button>
                        <el-button size="mini" @click.native.prevent="del(scope)" icon="el-icon-delete" type="danger" style="margin: 2px">删除</el-button>
                        <el-button size="mini" @click.native.prevent="resetPwd(scope.row)" type="primary" style="margin: 2px">重置密码</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="pagination-bar">
                <el-pagination class=""
                               @size-change="handleSizeChange"
                               @current-change="handleCurrentChange"
                               :current-page="currentPage"
                               :page-sizes="pageSizes"
                               :page-size="pageSize"
                               layout="total, sizes, prev, pager, next, jumper"
                               :total="total">
                </el-pagination>
            </div>

        </div>
        <el-dialog @close="()=>{this.dialogUserData = false}" title="用户详情" :visible.sync="dialogUserData">
            <div :model="userDataDetail" class="dialog-userData-detail">
                <div>
                    <el-row class="detail-title">基本信息</el-row>
                    <el-row>
                        <el-col :span="4" class="dialog-userData-name">账号：</el-col>
                        <el-col :span="20" >{{userDataDetail.account}}</el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="4" class="dialog-userData-name">用户名：</el-col>
                        <el-col :span="20" >{{userDataDetail.name}}</el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="4" class="dialog-userData-name">性别：</el-col>
                        <el-col :span="20">{{userDataDetail.sex}}</el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="4" class="dialog-userData-name">出生日期：</el-col>
                        <el-col :span="20">{{userDataDetail.birthday | dateFormatter}}</el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="4" class="dialog-userData-name">照片：</el-col>
                        <el-col :span="20" >
                            <img width="120" height="auto" class="dialog-userData-image" v-if="userDataDetail.userAvatar" :src="userDataDetail.userAvatar">
                        </el-col>
                    </el-row>
                </div>

                <div>
                    <el-row class="detail-title">业务信息</el-row>
                    <el-row>
                        <el-col :span="4" class="dialog-userData-name">所属部门：</el-col>
                        <el-col :span="20" >{{userDataDetail.departmentName}}</el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="4" class="dialog-userData-name">岗位：</el-col>
                        <el-col :span="20" >{{userDataDetail.jobName}}</el-col>
                    </el-row>
                </div>
                <div>
                    <el-row class="detail-title">联系信息</el-row>
                    <el-row>
                        <el-col :span="4" class="dialog-userData-name">手机号码：</el-col>
                        <el-col :span="20" >{{userDataDetail.phone}}</el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="4" class="dialog-userData-name">邮箱：</el-col>
                        <el-col :span="20" >{{userDataDetail.email}}</el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="4" class="dialog-userData-name">QQ：</el-col>
                        <el-col :span="20">{{userDataDetail.qq}}</el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="4" class="dialog-userData-name">简介：</el-col>
                        <el-col :span="20">{{userDataDetail.remark}}</el-col>
                    </el-row>
                </div>
            </div>
        </el-dialog>

        <el-dialog title="分配岗位" :visible.sync="dialogPosition">
            <el-form :model="positionForm" ref="positionForm" >
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="岗位" prop="role">
                            <job-select from="positionForm"/>
                            <!--<el-select size="small" v-model="positionForm.role" placeholder="请选择岗位">
                                <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id + ''"></el-option>
                            </el-select>-->
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer"  class="dialog-footer">
                <el-button @click="dialogPosition = false">取 消</el-button>
                <el-button type="primary" @click="submitPositionForm">确 定</el-button>
            </div>
        </el-dialog>
    </section>

</template>

<script>
    import Vue from 'vue'
    import axios from '~/plugins/axios';
    import { hasTargetNode,getClickTarget } from '../../../assets/js/common.js';
    import { mapGetters,mapMutations,mapActions } from 'vuex'
    import { Row,Col,Button,ButtonGroup,Input,Select,Option,FormItem,Form,Table,TableColumn,Pagination,MessageBox,Message,Icon,Dialog,Tree,Tooltip,Cascader } from 'element-ui'

    import {getDate, setToken, getCookie} from '~/utils/auth'
    import JobSelect from '~components/jobSelect.vue'


    Vue.use(Row)
    Vue.use(Col)
    Vue.use(Button)
    Vue.use(ButtonGroup)
    Vue.use(Input)
    Vue.use(Select)
    Vue.use(Option)
    Vue.use(Form)
    Vue.use(FormItem)
    Vue.use(Table)
    Vue.use(TableColumn)
    Vue.use(Pagination)
    Vue.use(Icon)
    Vue.use(Dialog)
    Vue.use(Tree)
    Vue.use(Tooltip)
    Vue.use(Cascader)

    Vue.prototype.$message = Message;
    Vue.prototype.$confirm = MessageBox.confirm;

    export default {
        components:{
            JobSelect
        },
        head(){
            return {
                title: "用户管理"
            }
        },
        data () {
            return {
                tabName: '用户管理',
                departmentTree: [],
                departmentTreeProps: {
                    label: 'name',
                    children: 'zones'
                },
                searchForm:{
                    account: "",
                    department: null,
                    departmentName:'',
                    showTree: false,
                    role: null,
                    name: ''
                },
                positionForm:{
                    department: null,
                    departmentName:'',
                    showTree: false,
                    role: null,
                    index: null
                },
                selectIndex: [],
                userDataDetail: {},
                dialogUserData: false,
                dialogPosition: false,
                positionFormRule: {
                    departmentName: [
                        {required: true,message: '请选择部门',trigger: 'change'}
                    ]
                }
            }
        },
        computed: {
            ...mapGetters({
                userDatas: "getUserDatas",
                currentPage: "getCurrentPage",
                pageSizes: "getPageSizes",
                pageSize: "getPageSize",
                total: "getTotal",
                editIndex: "getEditIndex",
                departmentList: "getDepartmentList",
                roleList: "getRoleList",
                axiosCode: "getAxiosCode",
                pageTabsList: 'getPageTabsList'
            }),
            userListParams () {
                return {
                    pageNum: this.currentPage,
                    pageSize: this.pageSize,
                    account: this.searchForm.account,
                    departmentId: this.searchForm.department,
                    jobId: this.searchForm.role,
                    name: this.searchForm.name
                }
            }
        },
        methods: {
            ...mapMutations([
                'dealEditIndex',
                'dealPageSize',
                'dealCurrentPage',
                'dealAxiosCode'
            ]),
            ...mapActions([
                'fetchUserDatas',
                'deleteUser',
                'regainStatus',
                'disableStatus',
                'freezeStatus',
                'resetPasswd',
                'updateRole',
                'fetchDepartmentTree'
            ]),

            //搜索条件加入cookie
            setFilterCookie(){
                let data = JSON.stringify(this.searchForm);
                setToken('userControlFilter',data);
            },


            removeEmptyKey(obj) {
                let con = {}
                for (let key in obj) {
                    if (obj.hasOwnProperty(key) && obj[key]){
                        con[key] = obj[key]
                    }
                }
                return con;
            },
            getRoleId(val) {
                this.searchForm.role = val[1]
            },
            getPositionFormRoleId(val) {
                this.positionForm.role = val[1]
            },
            getJobList() {
                this.$store.dispatch('getJobList')
            },
            loadNode(node, resolve) {

                axios.get(process.env.baseUrl + '/department/list', {params:{parentId:node.data.id||0}})
                    .then((ret)=>{
                        if(!ret){return}
                        return resolve(ret.data.data);
                    })

            },
            handleSearchCheckChange(data,checked) {
                if(checked) {
                    this.searchForm.department = data.id
                    this.searchForm.departmentName = data.name
                    this.searchForm.showTree = !this.searchForm.showTree
                    this.$refs.searchTree.setCheckedKeys([])
                    this.$refs.searchTree.setChecked(data,true)
                }
            },
            clearSearchForm() {
                this.searchForm = {
                    account: "",
                    department: null,
                    departmentName:'',
                    showTree: false,
                    role: null,
                    name: ''
                };
                this.$refs.jobName['setJobName']([]);
                this.$store.commit('PERSON_SETTING_FILTER',{data: this.searchForm});
            },
            query() {
                this.$store.commit('PERSON_SETTING_FILTER',{data: this.searchForm});
                this.setFilterCookie();
                this.getUserData(this.removeEmptyKey(this.userListParams));
            },
            edit(row) {
                let i = 0;
                for(i=0;i<this.pageSize;i++){
                    if(row.id == this.userDatas[i].id){
                        break
                    }
                }
                this.dealEditIndex({index:i});
                this.$router.push({name:'power-user-control-name',params:{name:'edit'}});
            },
            detail(id) {
                let i = 0;
                for(i=0;i<this.pageSize;i++) {
                    if(id == this.userDatas[i].id) {
                        break
                    }
                }
                this.userDataDetail = this.userDatas[i];
                this.dialogUserData = true;
            },
            handleSizeChange(index) {
                this.dealPageSize({pageSize:index})
                this.getUserData(this.userListParams)
            },
            handleCurrentChange(index) {
                this.dealCurrentPage({index:index})
                this.getUserData(this.userListParams)
            },
            getUserData(option){
                this.fetchUserDatas(option);
            },
            refresh() {
                this.getUserData(this.userListParams);
            },
            getAllIndex(selection){
                this.selectIndex = [];
                selection.forEach((n,i)=>{
                    this.selectIndex.push(this.userDatas.indexOf(n));
                });
            },
            del(scope){
                this.$confirm('确定要删除用户：'+scope.row.name, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    //这里调用删除接口
                    this.deleteUser({id: scope.row.id})
                        .then((response) => {
                            if(!response){return}
                            this.$store.commit('dealAxiosCode', {
                                val: response.data.code
                            })
                            //获取用户数据
                            this.getUserData(this.userListParams)
                            this.delayMessage('删除')
                        });
                })
            },
            delayMessage(msg)　{
                setTimeout(() => {
                    if(this.axiosCode === 0) {
                        this.$message({
                            type: 'success',
                            message: msg+'成功!'
                        });
                    }else{
                        this.$message.error(msg+'失败')
                    }
                },500)
            },
            freezeUser(index) {
                var _this = this
                this.$confirm('确定冻结?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    //这里调用冻结接口
                    this.freezeStatus({index:index,id:this.userDatas[index].id,status:2})
                        .then((response) => {
                            this.$store.commit('dealAxiosCode', {
                                val: response.data.code
                            })
                            if (response.data.code == 0) {
                                this.$store.commit('dealUserStatus', {
                                    preload: {index:index,id:this.userDatas[index].id,status:2}
                                })
                            }
                            this.delayMessage('冻结')
                        });
                       /* .then(function () {
                        _this.delayMessage('冻结')
                    })*/
                })
            },
            disableUser(index) {
                var _this = this
                this.$confirm('确定停用?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    //这里调用停用接口
                    this.disableStatus({index:index,id:this.userDatas[index].id,status:3})
                        .then((response) => {
                            this.$store.commit('dealAxiosCode', {
                                val: response.data.code
                            })
                            if (response.data.code === 0) {
                                this.$store.commit('dealUserStatus', {
                                    preload: {index:index,id:this.userDatas[index].id,status:3}
                                })
                            }
                            this.delayMessage('停用')
                        });
                       /* .then(function () {
                        _this.delayMessage('停用')
                    })*/
                })
            },
            regainUser(index) {
                var _this = this
                this.$confirm('确定启用?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    //这里调用启用接口
                    this.regainStatus({index:index,id:this.userDatas[index].id,status:1})
                        .then((response) => {
                            this.$store.commit('dealAxiosCode', {
                                val: response.data.code
                            })
                            if (response.data.code === 0) {
                                this.$store.commit('dealUserStatus', {
                                    preload: {index:index,id:this.userDatas[index].id,status:1}
                                })
                            }
                            this.delayMessage('启用')
                        });
                       /* .then(function () {
                        _this.delayMessage('启用')
                    })*/

                })
            },
            getTrueIndex(row){
                let i = 0;
                for(i=0;i<this.pageSize;i++){
                    if(row.id == this.userDatas[i].id){
                        break
                    }
                }
                return i
            },
            resetPwd(row) {
                var _this = this
                this.$confirm('确定重置'+row.name+'的账户密码为：123456', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    //这里调用重置密码
                    this.resetPasswd({id: row.id})
                        .then((response) => {
                            this.$store.commit('dealAxiosCode', {
                                val: response.data.code
                            })
                            this.delayMessage('重置密码')
                        });
                        /*.then(function () {
                        _this.delayMessage('重置密码')
                    })*/
                })
            },
            distributeRole(index) {
                this.dialogPosition = true
                this.positionForm.index = index
            },
            submitPositionForm() {
                var _this = this
                if (this.positionForm.role) {
                    //这里调用分配岗位接口
                    this.updateRole({id:this.userDatas[this.positionForm.index].id, jobid:this.positionForm.role})
                        .then((response) => {
                            this.$store.commit('dealAxiosCode', {
                                val: response.data.code
                            })
                            this.delayMessage('分配岗位')
                        });
                        /*.then(function () {
                        _this.delayMessage('分配岗位')
                    })*/
                    this.dialogPosition = false
                }else{
                    this.$message({
                        type: 'warning',
                        message: '请选择岗位!'
                    });
                }
            },
            treeBlurHide(){
                this.searchForm.showTree = false
                this.positionForm.showTree = false
            }
        },
        filters: {
            formatStatus(value){
                if (!value) return ''
                if (value === 1) return "正常使用"
                if (value === 2) return "冻结"
                if (value === 3) return "停用"
            },
            dateFormatter(val) {
                return val ? getDate(new Date(val),false) : ''
            }
        },
        created () {
            //pageTab
            if(process.BROWSER_BUILD) {
                if(this.pageTabsList[this.pageTabsList.length-1].name == 'CRM') {
                    let arr = this.pageTabsList;
                    arr[arr.length-1].name = this.tabName;
                    this.$store.commit('PAGETABSLIST',{data:arr})
                }
            }

        },
        mounted(){
            //从cookie里取出filter数据
            let parentUrl = getCookie('parentUrl');
            if(parentUrl == 'userControlEdit'){
                let item = getCookie('userControlFilter');
                if(item) this.searchForm = JSON.parse(item);
            }
            if(this.$store.getters.personSettingFilter != '') {
                this.searchForm = this.$store.getters.personSettingFilter;
            }
            //获取用户数据
            this.getUserData(this.userListParams)
            //获取岗位信息
            this.getJobList();
            this.refresh();
        }
    }
</script>

<style  lang="scss">
    .power-user-control{
        margin-top: 20px;
        .user-control-title{
            padding: 0;
        }
        .user-filter{
            padding: 10px 0;
            font-size: 12px;
            .el-form-item{
                margin-bottom: 15px;
            }
        }
        .user-filter .el-input{
            /*width: 150px;*/
        }
        .tool-bar{
            display: block;
            margin-bottom: 20px;
        a{
            display: inline-block;
            margin: 0 10px;
        }
        }
        .user-table{
            padding: 0;
            .el-table{
                /*font-size: 12px;*/
            }
        }
        .user-table table th {
            text-align: center!important;
        }
        .user-table .el-table .cell, .user-table .el-table th>div{
            padding-left: 8px;
            padding-right: 8px;
        }
        .el-table .cell{
            line-height: 20px;
        }

        .oprate-item{
            display: inline-block;
            padding:0 2px;
            text-decoration: none;
            color: #20a0ff;
        &:hover{
             text-decoration: underline;
         }
        }

        .pagination-bar{
            margin-top: 12px;
            overflow: hidden;
        .el-pagination{
            float: left;
        }
        }
        .dialog-userData-detail{
            border-top:1px solid #dfe6ec;
            border-left:1px solid #dfe6ec;
            background-color: #f1f2f2;
            .detail-title{
                text-align: center;
                font-weight: 700;
            }
            .dialog-userData-image{
                margin: 3px 0;
                vertical-align: middle;
            }
            .el-row{
                border-bottom:1px solid #dfe6ec;
                border-right:1px solid #dfe6ec;
                line-height: 24px;
            }
            .el-col{
                min-height: 24px;
                padding: 0 8px;
            }
            .dialog-userData-name{
                padding-right: 4px;
                text-align: right;
            & + div{
                    border-left:1px solid #dfe6ec;
                    background-color: #fff;
                }
            }
        }
        .dialog-userData-name{
        }
        .el-dialog__header{
            text-align: center;
        }
        .el-dialog{
            min-width: 645px;
        }
    }

</style>